import Qs from 'qs'
// const fs = require('fs')
import httpService from './http-service'
// console.log(!!fs)

import Arugument from './../Argument.js'

//服务请求路径前缀
const { 
  VUE_APP_API_REQUEST_PREFIX: API_PREFIX ,
  VUE_APP_PROXY_PATH: PROXY_PATH
} = process.env 


export const $BASE_URL = '/' + PROXY_PATH + '/' + API_PREFIX

//导出请求方法创建器
export function requestMethodCreator(method) {
  // 由于API期望是字符串，params期望对象，disposeResFun期望函数
  return function() {
    const argument = new Arugument(arguments)
    const API = argument.getTypeValueByIndex('string')
    const params = argument.getTypeValueByIndex('object')
    const disposeResFun = argument.getTypeValueByIndex('function')
    const config = {
      method,
      url: $BASE_URL + API,
      transformRequest: [function (data) {
        return data = Qs.stringify(data);
      }],
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: "json"
    }
    if(method === 'get') config.params = params
    else config.data = params
    //真正发送请求
    return httpService(config).then((res)=>{
      //如果配置有结果处理函数 执行函数并返回
      if(disposeResFun) {
        return disposeResFun(res)
      }
      return res
    }, (error)=>{
      if(disposeResFun) {
        return disposeResFun.$ConnectionErrorDispose(error)
      }
      return error
    })    
    .then((res)=>{
      return Promise.resolve(res)
    }).catch((error)=>{
      console.log('未连接服务端')
      return Promise.reject(error)
    })
  }
}
//错误路线，走错误路线，如果仍然返回reject错误，侧继续抛出，直到最后catch接收